package com.ics.atable.chat.service;

import com.ics.atable.chat.config.ChatClientServiceFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * llm service
 *
 * @author haohongbin
 */
@Service
public class LlmService {

    private static final String SYSTEM_PROMPT = "根据历史对话和用户输入，生成语义完整的自然语言问题";

    @Autowired
    private ChatClientServiceFactory chatClientServiceFactory;

    public String call(String prompt, String sessionId) {
        return chatClientServiceFactory
                .getOrCreateChatClient()
                .prompt()
                .system(SYSTEM_PROMPT)
                .user(prompt)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, sessionId))
                .call().content();
    }

    public String callWithSystemPrompt(String system, String user, String sessionId) {
        return chatClientServiceFactory
                .getOrCreateChatClient()
                .prompt()
                .system(system)
                .user(user)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, sessionId))
                .call().content();
    }

    /**
     * Stream the response to the user's prompt
     * @param prompt The user's input prompt
     * @return Streaming response
     */
    public Flux<ChatResponse> streamCall(String prompt) {
        return chatClientServiceFactory.getOrCreateChatClient().prompt().user(prompt).stream().chatResponse();
    }

    /**
     * Stream the response to the user's prompt with a system prompt
     * @param system The system prompt
     * @param user The user's input
     * @return Streaming response
     */
    public Flux<ChatResponse> streamCallWithSystemPrompt(String system, String user) {
        return chatClientServiceFactory.getOrCreateChatClient().prompt().system(system).user(user).stream().chatResponse();
    }
}
